var express = require('express')
var router = express.Router()
var mssqldb = require('../../Sql/Sql')


// 注册用户账户
router.post('/api/add', function (req, res) {
  // 注册的同时就要先建立一个 ‘我的钱包’ 账户，该账户不可删除
  if (!req.body.remark) {
    req.body.remark = ''
  }
  mssqldb.sql(`insert into Accounts values('${req.body.telephone}','${req.body.name}',${req.body.expend},'${req.body.remark}',${req.body.importance})`, function (err, result) {
    if (err) {
      console.log(err)
      return
    }
    // 注册成功
    let response = {
      message: '成功',
      data: {
        status: 200,
        errorCode: 0, // 注册成功
      }
    }
    res.json(response)
  })
})


// 获取用户账户
router.get('/api/account', function (req, res) {
  mssqldb.sql(`select * from Accounts where telephone=${req.query.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)

      return
    }
    let response = {
      data: {
        errorCode: 0, // 成功
        data: result.recordset
      }
    }
    res.json(response)
  })
})


// 修改记录
router.put('/api/alter', function (req, res) {
  mssqldb.sql(`update Accounts set name='${req.body.name}',expend=${req.body.expend},remark='${req.body.remark}' where telephone='${req.body.telephone}' and id = ${req.body.id}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    let response = {
      errorCode: 0, // 成功
    }
    res.json(response)
  })
})


// 删除记录
router.delete('/api/del/:id', function (req, res) {
  mssqldb.sql(`delete from Accounts where id = ${req.params.id}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    let response = {
      errorCode: 0, // 成功
    }
    res.json(response)
  })
})


module.exports = router